package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.zk.ZKClientUtil;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    public static Object createProxy(Class serviceClass, String ip, int port) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = new RpcClient(ip, port);
                        System.out.println("==========向服务端 "+ ip +":"+ port +"  连接成功==========");

                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });
    }

    public static Object createProxy1(Class serviceClass, String ip, int port) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);

                        // 基于zk的负载均衡：从zk上获取处理时间较小节点使用
                        long minTime = Integer.MAX_VALUE;
                        String server="";
                        ZkClient zkClient = ZKClientUtil.getInstance();
                        List<String> children = zkClient.getChildren(ZKClientUtil.pathPre);
                        for(String child : children){
                            String path = ZKClientUtil.pathPre + "/" + child;
                            Long currTime = Long.valueOf(JSONObject.toJSONString(zkClient.readData(path)));
                            System.out.println("==========ZooKeeper path: "+path+" === data:" + JSONObject.toJSONString(currTime));
                            if(currTime <= minTime){
                                minTime = currTime;
                                server = child;
                            }
                        }
                        String[] info = server.split("_");
                        //2.创建RpcClient对象
                        RpcClient rpcClient = new RpcClient(info[0], Integer.valueOf(info[1]));
//                        RpcClient rpcClient = ConnZKServer.SERVER_MAP.get(server);
//                        System.out.println("==========RpcClientProxy 向服务端 "+ info[0] +":"+ Integer.valueOf(info[1]) +"  连接成功==========");

                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            System.out.println("服务端"+ info[0]+ ":" +Integer.valueOf(info[1])+ " responseMsg data:" + JSONObject.toJSONString(responseMsg));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });
    }
}
